﻿using NLog;
using playwrightJu3.Windows;
using System;
using System.Configuration;
using System.Data;
using System.Threading.Tasks;
using System.Windows;

namespace playwrightJu3
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        protected override void OnStartup(StartupEventArgs e)
        {
            logger.Info("App started.");
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            base.OnStartup(e);
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exception = e.ExceptionObject as Exception;
            if (exception != null)
            {
                HandleException(exception);
                logger.Error(exception);
            }
            else
            {
                HandleException(new Exception("An unhandled exception occurred and could not be identified."));
                logger.Error("An unhandled exception occurred and could not be identified.");
            }

        }

        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            e.SetObserved(); // Prevents the application from crashing
            HandleException(e.Exception);
            logger.Error(e.Exception);
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true; // Prevents the application from crashing
            HandleException(e.Exception);
            logger.Error(e.Exception);
        }


        private void HandleException(Exception ex)
        {
            ExceptionDialog dialog = new ExceptionDialog(ex);
            dialog.ShowDialog();
            //MessageBox.Show($"An error occurred: {ex.ToString()}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }


}
